<!--
 * @Descripttion: 
 * @Author: 颜博骏 bojun@ssc-hn.com
 * @Date: 2024-04-10
 * @LastEditors: 颜博骏 bojun@ssc-hn.com
 * @LastEditTime: 2024-06-21
 * @Description: 
-->
<template>
  <div class="ssc-list">
    <div class="ssc-search">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="名称">
            <a-input v-model:value="searchParam.channelName" placeholder="请输入渠道名称" />
          </a-form-item>
        </a-col>
        <a-col :span="18">
          <a-row justify="end">
            <a-button @click="clear()">重置</a-button>
            <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
          </a-row>
        </a-col>
      </a-row>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header">
        <span class="ssc-table-header-title">组织结构</span>
        <div v-if="!addButtonVisible">
          <a-button type="primary" @click="addTopChannel(1)">
            <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
            新增一级渠道
          </a-button>
          <!-- 
          一期暂不做批量删除
          <a-button type="primary" danger @click="batchDelete()" style="margin-left: 15px">
            <template #icon><close-outlined :style="{ 'font-weight': 'bold' }" /></template>
            批量删除
          </a-button> -->
        </div>
      </div>
      <!-- <a-table v-if="table.initialLoaded" :columns="table.columns" :data-source="table.datas" :defaultExpandedRowKeys="table.expandedRowKeys" :loading="table.loading"> -->
      <a-table v-if="table.initialLoaded" :columns="table.columns" :data-source="table.datas" :loading="table.loading" :pagination="paginationConf" :row-selection="rowSelection" @expand="OnExpandSubChannels" @change="onPageChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a @click="addUnderling(2, record.channelId, record.channelName)" v-if="record.createFlag === 1">添加下级</a>
              <a-divider type="vertical" v-if="record.createFlag === 1" />
              <a @click="edit(0, record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="allot(record.channelId)">分配码</a>
              <a-divider type="vertical" />
              <a-popconfirm title="删除当前渠道，需确定当前渠道没有下级渠道，否则将删除失败" @confirm="dele(record.channelId)">
                <a class="color-error">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <div class="modal">
      <AllotCode v-model:visible="allotCode.visible" :channelId="allotCode.channelId" />
    </div>
  </div>
</template>

<script setup lang="ts">
  // import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue'   一期暂不做批量删除
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { message, type TreeProps } from 'ant-design-vue'
  import { onMounted, reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'

  import { requestCheckOneLevel, requestDeleteChannel, requestGetChannelList, requestGetSubChannelList } from '/@/api/business/tracecode/channel/index'
  import type { GetChannelSublistTypes } from '/@/api/business/tracecode/channel/model'
  import { HttpCodeEnum } from '/@/enums/httpEnum'

  import AllotCode from './components/AllotCode.vue'
  const router = useRouter()

  const paginationConf = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total) => `共${total}条`,
  })
  const addButtonVisible = ref(false)

  /** 批量选择渠道Id */
  const channelIds = ref<number[]>()

  /** 搜索条件*/
  const searchParam = reactive({
    pageIndex: 1,
    pageSize: 10,
    channelName: '',
  })

  /** 表格配置 */
  const table = reactive({
    columns: [
      { title: '渠道名称', dataIndex: 'channelName', key: 'channelName' },
      { title: '下级渠道', dataIndex: 'subCount' },
      {
        title: '是否允许自建下级渠道',
        dataIndex: 'createFlag',
        customRender: ({ record }) => {
          if (record.createFlag === 1) return '是'
          else return '否'
        },
      },
      { title: '创建时间', dataIndex: 'createdTime' },
      { title: '操作', key: 'action' },
    ],
    datas: [] as TreeProps['treeData'],
    initialLoaded: false,
    loading: false,
    // expandedRowKeys: computed(() => [(table.datas as TreeDataItem[])[0]?.key.toString()]),
  })

  /** 选择功能的配置 */
  const rowSelection = ref({
    checkStrictly: true,
    onChange: (selectedRowKeys: number[]) => {
      channelIds.value = selectedRowKeys
    },
  })

  /** 搜索*/
  const search = () => {
    searchParam.pageIndex = 1
    paginationConf.current = 1
    initData()
  }
  /** 重置*/
  const clear = () => {
    searchParam.channelName = ''
    search()
  }

  /** 下级渠道展开 */
  const OnExpandSubChannels = (expanded, record) => {
    if (expanded && !record.isExpanded) {
      record.isExpanded = 1
      const channelId = record.channelId
      requestGetSubChannelList({ channelId }).then((res) => {
        const subList = res.responseData as any
        const formatSubList = subList.map((item: any) => {
          if (item.subCount !== 0) {
            return {
              ...item,
              children: [],
              key: item.channelId,
              isExpanded: 0,
            }
          } else {
            return { ...item, key: item.channelId, isExpanded: 0 }
          }
        })
        record.children = formatSubList
      })
    }
    return
  }

  /** 分配码弹窗 */
  const allotCode: { visible: boolean; channelId: string } = reactive({
    visible: false,
    channelId: '',
  })

  /**
   * 初始化数据
   */
  const initData = async () => {
    table.loading = true
    const { pageIndex, pageSize, channelName } = searchParam
    const { responseData } = await requestGetChannelList({ pageIndex, pageSize, channelName })
    paginationConf.total = responseData.total
    table.datas = responseData.list.map((item: GetChannelSublistTypes.IResponse) => {
      return {
        ...item,
        key: item.channelId,
        children: item.subCount === 0 ? undefined : [],
        istop: 1,
        isExpanded: 0,
      }
    })

    table.loading = false
    table.initialLoaded = true
  }

  const onPageChange = (pagination) => {
    searchParam.pageIndex = pagination.current
    paginationConf.current = pagination.current
    initData()
  }

  /**
   * 编辑
   * @param level level 新增级别：非新建 0；一级新建 1；其他新建 2
   */
  const edit = (level: number, record: any) => {
    const istop = record.istop ? record.istop : 0
    router.push({
      name: 'channel-manage-add',
      query: {
        pageType: level, // 编辑：0；一级新建：1；其他新建：2
        channelId: record.channelId,
        istop,
      },
    })
  }

  /**
   * 分配码弹窗
   */
  const allot = (channelId: string) => {
    allotCode.visible = true
    allotCode.channelId = channelId
  }

  /**
   * 新增一级渠道
   * @param level 新增级别：非新建 0；一级新建 1；其他新建 2
   */
  const addTopChannel = (level: number) => {
    router.push({
      name: 'channel-manage-add',
      query: {
        pageType: level,
      },
    })
  }

  /**
   * 批量删除
   */
  // 一期暂不做批量删除
  // const batchDelete = async () => {
  //   console.log('批量删除')
  //   const Ids = channelIds.value as number[]
  //   console.log(Ids)

  //   const { responseCode } = await requestBatchDelete({ channelIds: Ids })
  //   if (responseCode === HttpCodeEnum.SUCCESS) {
  //     message.success('删除成功')
  //     initData()
  //   }
  // }

  /**
   * 添加下级
   * @param deptId 部门id
   * @param level 新增级别：非新建 0；一级新建 1；其他新建 2
   */
  const addUnderling = (level: number, channelId: number, channelName: string) => {
    router.push({
      name: 'channel-manage-add',
      query: {
        pageType: level, // 编辑：0；一级新建：1；其他新建：2
        channelName,
        channelId,
      },
    })
  }

  /**
   * 删除
   * @param channelId 渠道id
   */
  const dele = async (channelId: number) => {
    const { responseCode } = await requestDeleteChannel({ channelId })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('删除成功')
      initData()
    }
  }
  /** 获取当前账号权限 */
  const getCurrentRight = () => {
    requestCheckOneLevel({}).then((res) => {
      addButtonVisible.value = res.responseData as boolean
    })
  }

  onMounted(() => {
    initData()
    getCurrentRight()
  })
</script>

<style scoped lang="less">
  .color-error {
    color: red;
  }
</style>
